#include<iostream>
#include<pthread.h>
using namespace std;

pthread_mutex_t mux=PTHREAD_MUTEX_INITIALIZER;

pthread_cond_t cond=PTHREAD_COND_INITIALIZER;

int x=10;

int y=20;

void* tpr(void* para)
{	
	pthread_mutex_lock(&mux);

	while(x>y){
		pthread_cond_wait(&cond,&mux);//一旦唤醒，就会加锁
	}

	x=20;
	y=10;
	cout<<"t1"<<endl;
	
	pthread_mutex_unlock(&mux);

	pthread_cond_signal(&cond);
	return ((void*)1);
}

void* tpr2(void* para)
{	
	pthread_mutex_lock(&mux);

	while(x<y){
		pthread_cond_wait(&cond,&mux);//一旦唤醒，就会加锁
	}

	x=10;
	y=20;
	cout<<"t2"<<endl;
	
	pthread_mutex_unlock(&mux);	

	pthread_cond_signal(&cond);
	return ((void*)2);
}
int main()
{	
	pthread_t tid,tid2;
	pthread_mutex_lock(&mux);
	int ret=pthread_create(&tid,nullptr,tpr,nullptr);
	int ret2=pthread_create(&tid2,nullptr,tpr2,nullptr);

	if(ret || ret2){
		cout<<"error"<<endl;
		exit(1);
	}
	
	cout<<"thread create finished"<<endl;
	pthread_mutex_unlock(&mux);
	void *retv,*retv2;
	pthread_join(tid,&retv);
	pthread_join(tid2,&retv2);

	cout<<x<<"and"<<y<<endl;
}
